package com.warm.test.redis;

import cn.dev33.satoken.annotation.SaIgnore;
import com.warm.test.redis.entity.UserM;
import com.warm.dict.utils.DictUtils;
import com.warm.cache.utils.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.data.annotation.CachePut;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.validation.annotation.Valid;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 缓存demo
 *
 * @author warm
 */
@Slf4j
@SaIgnore
@Valid
@Controller
@Mapping("/demo/cache/")
public class CacheController {

    /**
     * 执行结果缓存10秒，使用 key=test:${label} 并添加 test 标签
     */
    // @Cache(service = "cache1", key = "test:${label}", tags = "test", seconds = 100)
    @Mapping("/set")
    public Object test(int label) {
        // 通过切换select-pom中
        CacheUtil.setCacheObject("测试1", new UserM(1, "123"));
        CacheUtil.setCacheObject("测试2", new UserM(1, "123"), 2000);
        CacheUtil.setCacheObject("测试3", new UserM(1, "123"), 2000);
        CacheUtil.setCacheObject("测试4", new UserM(1, "123"), 2000);
        CacheUtil.setCacheObject("测试14", new UserM(1, "123"), 2000);
        CacheUtil.setCacheObject("测试1:5", new UserM(1, "123"), 2000);
        log.info("hasKey:{}", CacheUtil.hasKey("测试1"));
        UserM userM = CacheUtil.getCacheObject("测试1", UserM.class);
        log.info("getCacheObject:{}", userM);

        CacheUtil.deleteObject("测试2");
        CacheUtil.deleteObject(Arrays.asList("测试3", "测试4"));
        log.info("keys:{}", CacheUtil.keys("测试1*"));

        List<UserM> userMS = new ArrayList<>();
        userMS.add(new UserM(1, "121"));
        userMS.add(new UserM(2, "122"));
        userMS.add(new UserM(3, "123"));
        userMS.add(new UserM(4, "124"));
        DictUtils.setDictCache("测试5", userMS);
        log.info("getCacheObjectList:{}", CacheUtil.getCacheObjectList("测试5", UserM.class));


        return new Date();
    }

    /**
     * 行后，清除 tag=test 的所有缓存，并更新 key=test_${label} 的缓存块
     */
    @CachePut(key = "test_${label}")
    @CacheRemove(tags = "test")
    @Mapping("/clear")
    public String clear(int label) {
        return "清除成功(其实无效)-" + new Date();
    }

    /**
     * 执行后，更新 key=test:${label} 的缓存
     */
    @CachePut(key = "test:${label}")
    @Mapping("/put")
    public Object clear2(int label) {
        return new Date();
    }
}
